import tkinter as tk
from tkinter import messagebox
import subprocess
import sys
import threading
from pynput import keyboard
import pyperclip


def install_missing_libraries():
    required_libraries = ['pynput', 'pyperclip']
    for library in required_libraries:
        try:
            __import__(library)
        except ImportError:
            try:
                subprocess.check_call([sys.executable, "-m", "pip", "install", library])
            except subprocess.CalledProcessError as e:
                messagebox.showerror("安装错误", f"安装 {library} 库时出错: {e}")
                sys.exit(1)


install_missing_libraries()


class KeyboardMonitorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("键盘监测脚本")
        self.root.geometry("400x300")

        self.label = tk.Label(root, text="请输入要粘贴的内容:")
        self.label.pack(pady=10)

        self.input_text = tk.Entry(root, width=30)
        self.input_text.pack(pady=5)
        self.input_text.insert(0, "您好，这边是领星ERP售前商务咨询，您已接入人工，请问有什么可以帮您？")

        self.start_button = tk.Button(root, text="启动", command=self.start_monitoring)
        self.start_button.pack(pady=20)

        self.pause_button = tk.Button(root, text="暂停", command=self.pause_monitoring, state=tk.DISABLED)
        self.pause_button.pack(pady=10)

        self.monitoring = False
        self.listener = None

    def on_press(self, key):
        if self.monitoring:
            try:
                if key == keyboard.Key.enter:
                    paste_text = self.input_text.get()
                    pyperclip.copy(paste_text)
            except AttributeError:
                pass

    def start_monitoring(self):
        if not self.monitoring:
            self.monitoring = True
            self.start_button.config(state=tk.DISABLED)
            self.pause_button.config(state=tk.NORMAL)
            self.listener = keyboard.Listener(on_press=self.on_press)
            self.listener.start()

    def pause_monitoring(self):
        if self.monitoring:
            self.monitoring = False
            self.start_button.config(state=tk.NORMAL)
            self.pause_button.config(state=tk.DISABLED)
            if self.listener:
                self.listener.stop()


if __name__ == "__main__":
    root = tk.Tk()
    app = KeyboardMonitorApp(root)
    root.mainloop()
    